package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.*;
import com.acme.bankapp.domain.exception.*;

/**
 * Class provides service functionality
 * @author alex
 */
public class BankService {
	/**
	 * @param bank the bank
	 * @param client the client
	 * @throws ClientsMaxException 
	 * @throws ClientExistsException 
	 */
	public static void addClient(Bank bank, Client client) throws ClientsMaxException, ClientExistsException {
		AbstractAccount account = (AbstractAccount) client.getAccount();
		account.setClient(client);
		
		bank.addClient(client);
		BankDataLoaderService.saveBank(bank);
	}
	
	/**
	 * @param bank the bank
	 * @param client the client
	 * @return the client account
	 */
	public static Account getClientAccount(Bank bank, Client client) {
		Client clientOfBank = bank.getClient(client);
		if (clientOfBank != null) {
			return clientOfBank.getAccount();
		} else {
			return null;
		}
	}
	
	/**
	 * Prints on console the clients list
	 * @param bank the bank
	 */
	public static void printClientsList(Bank bank) {
		while (bank.hasNextClient()) {
			System.out.println(bank.getNextClient());
		}
	}
	
	/**
	 * Prints on console the accounts list
	 * @param bank the bank
	 */
	public static void printAccountsList(Bank bank) {
		while (bank.hasNextClient()) {
			System.out.println(bank.getNextClient().getAccount());
		}
	}
	
	/**
	 * @param bank the bank
	 * @param client the client
	 * @param x the money
	 * @throws ClientNotFoundException 
	 * @throws NotEnoughFundsException 
	 */
	public static void withdrawClientAccount(Bank bank, Client client, double x) throws ClientNotFoundException, NotEnoughFundsException {
		Account account = BankService.getClientAccount(bank, client);
		if (account != null) {
			account.withdraw(x);
			BankDataLoaderService.saveBank(bank);
		} else {
			throw new ClientNotFoundException();
		}
	}
	
	/**
	 * @param bank the bank
	 * @param client the client
	 * @param x the money
	 * @throws ClientNotFoundException 
	 */
	public static void depositClientAccount(Bank bank, Client client, double x) throws ClientNotFoundException {
		Account account = BankService.getClientAccount(bank, client);
		if (account != null) {
			account.deposit(x);
			BankDataLoaderService.saveBank(bank);
		} else {
			throw new ClientNotFoundException();
		}
	}
	
	/**
	 * @param bank the bank
	 * @param client the client
	 * @return the maximum amount to withdraw
	 * @throws ClientNotFoundException 
	 */
	public static double getMaximumAmountToWithdraw(Bank bank, Client client) throws ClientNotFoundException {
		Account account = BankService.getClientAccount(bank, client);
		if (account != null) {
			return account.maximumAmountToWithdraw();
		} else {
			throw new ClientNotFoundException();
		}
	}
}
